package com.hqyj.config.shiro;

import com.hqyj.user.entity.User;
import com.hqyj.user.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Objects;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    private User user = new User();

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String userName = (String) token.getPrincipal();
        user.setUserName(userName);
        User login = userService.login(user);
        if (Objects.isNull(login)){
            throw new UnknownAccountException();
        }
        redisTemplate.opsForValue().set("user",login);
        return new SimpleAuthenticationInfo(
                userName
                ,login.getUserPwd()
                ,new Md5Hash(userName)
                ,this.getName());
    }

}
